<?php
namespace app\admin\controller\soft;
use app\providers\BaseController;
use think\facade\Cookie;
use think\facade\Db;
use auth\Auths;
use auth\GoogleAuth;
use app\admin\service\ShieldIp as ShieldIpService;
use app\admin\service\Security as SecurityService;
use hg\apidoc\annotation as Apidoc;
use think\captcha\facade\Captcha;

/**
 * @Apidoc\Title("系统登录")
 * @Apidoc\Group("base")
 * @Apidoc\Sort(1)
 */
class Auth extends BaseController
{
	// 默认的设置参数
	private $name = 'system_user';   					// 用户表名-全称
	private $key = 'user_guid';		 					// 用户表名-全称
	private $login_code_field = 'user_code'; 			// 登录账号字段
	private $login_pwd_field = 'user_pwd';				// 登录密码字段
	
	/**
     * @Apidoc\Title("登录")
     * @Apidoc\Desc("系统登录")
     * @Apidoc\Author("weifashi")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("user_name",require=true,default="admin",desc="用户名" )
     * @Apidoc\Param("user_pwd", require=true, default="1",desc="密码" )
     * @Apidoc\Param("captcha", require=true, default="",desc="验证码" )
     * @Apidoc\Returned("token",  desc="token")
     * @Apidoc\After(event="setGlobalHeader",key="x-admin-token",value="res.data.data",desc="我的全局Header参数")
     * @global login false
     */
    public function login(ShieldIpService $shieldIp,$user_name,$user_pwd,$captcha='',$google_code='')
    {
        $land_ip = request()->ip();
    	if( empty($user_name) ) return  \Api::ReError('用户名不能为空!');
		if( empty($user_pwd) ) return  \Api::ReError('密码不能为空!');
        if( !captcha_check($captcha) && env('APP_DEBUG') != true) return  \Api::ReError('验证码错误!');
        if( !$shieldIp->verifyIp(0,$user_name,$land_ip) ) return \Api::ReError('ip已被禁用！');
        
		$userInfo = Db::name( $this->name )
                ->where( $this->login_code_field ,"$user_name")
                ->where( $this->login_pwd_field , md5('wei'.md5($user_pwd)) )
                ->where('user_type','1')
                ->find();
        
        //密码错误        
		if(!$userInfo){
		    $num = $shieldIp->addErrorNum(0,$user_name,$land_ip);
            $loginErrorNum = getSystem('base_login_error_num') ?: 0;
            if( $loginErrorNum > 0 ){
                $surplus = $loginErrorNum-$num; 
                return  \Api::ReError("密码错误,已{$num}次登录失败,剩余{$surplus}次！");
            }
			return  \Api::ReError('密码错误!');
		}
        
        //安全验证
        $security = (new SecurityService)->getInfo( 0, $userInfo['user_id']);
        if($security && $security->is_google_auth_bind && $security->login_security_type == 2){
            if(!$google_code)  return \Api::ReError('请输入谷歌验证码！');
            if( !GoogleAuth::instance()->verifyCode($security->google_secret,$google_code) ){
                $num = $shieldIp->addErrorNum(0,$user_name,$land_ip);
                $loginErrorNum = getSystem('base_login_error_num') ?: 0;
                if( $loginErrorNum > 0){
                    $surplus =$loginErrorNum-$num; 
                    return  \Api::ReError("谷歌验证码错误,已{$num}次登录失败,剩余{$surplus}次！");
                }
                return \Api::ReError('谷歌验证码错误！');    
            }
        }
        
        //是否禁用
		if( $userInfo['is_enable'] == "0" ){
			return  \Api::ReError('该账户已被禁用!');
		}
		
		/* 登录成功-获取token */
		$tokens = Auths::instance('admin')->expTime(360)->login($userInfo);
		
		/*登录成功-更新对应信息*/
		$data['land_time'] = (new \DateTime() )->format('Y-m-d H:i:s');
		$data['land_ip'] = request()->ip();
		$data['land_ip'] = $userInfo['land_ip'] = $land_ip;
		$data['only_no'] = md5( $tokens['access_token'] );
		if( ! Db::name($this->name)->where($this->key,$userInfo[$this->key])->update($data) ){
			return  \Api::ReError('更新最后登录时间失败!');
		}
		
		/* 登录成功-记录登录 */
		/*获取tokeen-更新对应信息*/
	    Cookie::set('x-admin-token',$tokens['access_token']);
	    Cookie::set('x-admin-refresh-token',$tokens['refresh_token']);
        
		/* 返回 */
		return  \Api::ReSucess($tokens['access_token'],'登录成功!');
    }
	
	
    /**
     * 退出登录
     * @Apidoc\Url("/admin/soft/auth/logout")
     * @Apidoc\Method("POST")
     * @Apidoc\Returned("退出成功")
     * @global login false
     */
    public function logout()
    {
    	Auths::instance('admin')->logout( Cookie::get('x-admin-token') );
        Cookie::set('x-admin-token','');   Cookie::set('x-admin-refresh-token','');
        return json(array("code"=>0,"data"=>"","msg"=>"退出成功"));
    }
    
}
